// app.js
const { authManager } = require('./utils/auth.js')

// 全局页面登录/权限守卫
const LOGIN_WHITELIST = [
  '/pages/login/login',
]
const __originalPage__ = Page
Page = function (opts) {
  const origOnShow = opts.onShow
  const origOnLoad = opts.onLoad
  // 包装 onLoad
  opts.onLoad = function (...args) {
    const route = `/${this.route || ''}`
    if (!LOGIN_WHITELIST.includes(route)) {
      if (route.indexOf('/admin/') >= 0) {
        if (!authManager.pageAdminCheck()) return
      } else {
        if (!authManager.pageLoginCheck()) return
      }
    }
    if (typeof origOnLoad === 'function') origOnLoad.apply(this, args)
  }
  // 包装 onShow，确保返回后仍校验
  opts.onShow = function (...args) {
    const route = `/${this.route || ''}`
    if (!LOGIN_WHITELIST.includes(route)) {
      if (route.indexOf('/admin/') >= 0) {
        if (!authManager.pageAdminCheck()) return
      } else {
        if (!authManager.pageLoginCheck()) return
      }
    }
    if (typeof origOnShow === 'function') origOnShow.apply(this, args)
  }
  return __originalPage__(opts)
}

App({
  onLaunch() {
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
  },
  globalData: {
    userInfo: null,
    serverUrl: 'http://192.168.1.53:8000/WxApi'
  },
  // 保存登录信息（登录成功后调用）
  setLoginInfo({ username, password, userInfo }) {
    try {
      authManager.saveLoginInfo(username, password, userInfo)
      this.globalData.userInfo = userInfo
    } catch (e) {
      console.error('保存登录信息失败', e)
    }
  },
  // 获取当前登录状态
  isLoggedIn() {
    const status = authManager.checkLoginStatus()
    this.globalData.userInfo = status.userInfo || null
    return status.isLoggedIn
  },
  // 退出登录（全局）
  logout() {
    authManager.logout()
    this.globalData.userInfo = null
  }
})
